package com.suse.common.util.request;

import cn.hutool.core.util.ObjectUtil;
import com.suse.common.util.core.StringUtil;
import com.suse.common.util.response.ResponseUtil;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class RequestUtil {

    public static HttpServletRequest getRequest() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (ObjectUtil.isNull(requestAttributes)) {
            return null;
        }
        return requestAttributes.getRequest();
    }

    public static String getIp() {
        HttpServletRequest request = getRequest();
        if (ObjectUtil.isNull(request)) {
            return null;
        }
        return getRequest().getRemoteAddr();
    }

    public static String getUserAgent() {
        HttpServletRequest request = getRequest();
        if (ObjectUtil.isNull(request)) {
            return null;
        }
        return getRequest().getHeader("User-Agent");
    }

    public static String getSystem() {
        String userAgent = getUserAgent();
        if (StringUtil.isEmpty(userAgent)) {
            return null;
        }
        String[] split = userAgent.split(" ");
        return split[1].split(" ")[0].substring(1);
    }

    public static String getBrowser() {
        String userAgent = getUserAgent();
        if (StringUtil.isEmpty(userAgent)) {
            return null;
        }
        String[] split = userAgent.split(" ");
        return split[split.length - 3].split("/")[0];
    }

    public static boolean isXMLHttpRequest() {
        HttpServletRequest request = getRequest();
        if (ObjectUtil.isNull(request))  {
            return false;
        }
        return isXMLHttpRequest(request);
    }

    public static boolean isXMLHttpRequest(HttpServletRequest request) {
        if (ObjectUtil.isNull(request)) {
            return false;
        }
        String xRequestedWith = request.getHeader("X-Requested-With");
        return "XMLHttpRequest".equals(xRequestedWith);
    }

    public static void forword(String path) {
        HttpServletRequest request = getRequest();
        HttpServletResponse response = ResponseUtil.getResponse();
        if (ObjectUtil.isNull(request)) {
            return;
        }
        if (ObjectUtil.isNull(response)) {
            return;
        }
        try {
            request.getRequestDispatcher(path).forward(request,response);
        } catch (ServletException | IOException e) {
            e.printStackTrace();
        }
    }

}
